﻿CREATE PROCEDURE dbo.s_Page_Insert_Ex
	@LoanID int,
	@ImageTypeID int,
	@PageAfter int,
	@Glossary text = null,
	@PageTypeID int = null,
	@Data image = null
AS

IF @Data IS NULL BEGIN
	RAISERROR('No Data provided for PageType %d',16,1,@PageTypeID)
	RETURN
END

DECLARE @PageNumber int SET @PageNumber = @PageAfter + 1

-- Create Image Folder
IF NOT EXISTS(SELECT * FROM t_Image WHERE LoanID = @LoanID AND ImageTypeID = @ImageTypeID)
	INSERT INTO t_Image(LoanID,ImageTypeID) VALUES(@LoanID,@ImageTypeID)

IF @PageNumber <= 0 -- move @PageNumber from the end
	SELECT @PageNumber = COUNT(*) + @PageNumber+1 FROM GetPageNumbers(@LoanID,@ImageTypeID,-1)

--RAISERROR('Ready to insert page %d',16,1,@PageNumber)

IF @@ERROR <> 0 RETURN
-- Insert Page Container
INSERT INTO t_Page (ImageID,Glossary,PageNumber)
SELECT ID,@Glossary,@PageNUmber FROM t_Image
WHERE LoanID = @LoanID AND ImageTypeID = @ImageTypeID

IF @@ERROR <> 0 OR @PageTypeID IS NULL BEGIN
	EXEC sh_Debug_Print '@PageNumber:$0',@PageNumber
	RETURN
END
-- Insert Data into Storage
EXEC s_Page_Update @LoanID,@ImageTypeID,@PageTypeID,@PageNumber,@Data

RETURN @PageNumber
